#include"head.h"
#include"add_friends.h"
extern clients *user;  // 访问全局链表头
// 去除字符串末尾的换行符
void remove_str(char *str) 
{
    size_t len = strlen(str);
    if (len > 0 && str[len - 1] == '\n') {
        str[len - 1] = '\0';
    }
}
void add_friend(clients *newuser, const char *friend_name)
{
    pthread_mutex_lock(&userMutex);

    // 1. 查找是否存在该用户
    clients *target = NULL;
    for (clients *p = user->next; p != user; p = p->next) 
    {
        if (strncmp(p->name, friend_name,strlen(friend_name)-1) == 0) {
            target = p;
            break;
        }
    }

    if (!target) 
    {
        char msg[64];
        snprintf(msg, sizeof(msg), "添加失败：用户 %s 不存在或不在线\n", friend_name);
        send(newuser->connfd, msg, strlen(msg), 0);
        pthread_mutex_unlock(&userMutex);
        return;
    }

    // 2. 查找好友链表中是否已经存在
    friends_t *f;
    for (f = newuser->friends->next; f != newuser->friends; f = f->next) 
    {
        if (strncmp(f->friendname, friend_name,strlen(friend_name)-1) == 0) 
        {
            send(newuser->connfd, "该用户已经是你的好友了\n", 36, 0);
            pthread_mutex_unlock(&userMutex);
            return;
        }
    }
    // 3. 插入好友
    friends_t *newf = calloc(1, sizeof(friends_t));
    strcpy(newf->friendname, friend_name);
    newf->next = newuser->friends;
    newf->prev = newuser->friends->prev;
    newuser->friends->prev->next = newf;
    newuser->friends->prev = newf;

    // 给 target 也插入 newuser 为好友，实现双向
    friends_t *newf2 = calloc(1, sizeof(friends_t));
    strcpy(newf2->friendname, newuser->name);
    newf2->next = target->friends;
    newf2->prev = target->friends->prev;
    target->friends->prev->next = newf2;
    target->friends->prev = newf2;    

    char msg[64];
    snprintf(msg, sizeof(msg), "成功添加 %s 为好友\n", friend_name);
    send(newuser->connfd, msg, strlen(msg), 0);
    pthread_mutex_unlock(&userMutex);
}
//显示好友列表
void show_friends(clients *newuser)
{
    pthread_mutex_lock(&userMutex);
    friends_t *f = newuser->friends->next;
    if (f == newuser->friends) 
    {
        send(newuser->connfd, "你还没有添加任何好友\n", 48, 0);
    } 
    else
    {
        char buffer[512] = "你的好友列表：\n";
        while (f != newuser->friends) 
        {
            strcat(buffer, "- ");
            strcat(buffer, f->friendname);
            strcat(buffer, "\n");
            f = f->next;
        }
        send(newuser->connfd, buffer, strlen(buffer), 0);
    }
    pthread_mutex_unlock(&userMutex);
}
void save_friends(char *filename)
{
    FILE *fp = fopen(filename,"a+");
    if (fp == NULL)
    {
        perror("friend.txt fail to open");
        exit(1);
    }
    clients *tmp = user->next;
    for ( ; tmp != user; tmp = tmp->next)
    {   remove_str(tmp->name);
        fprintf(fp,"[username]:%s\n[friends list]:\n",tmp->name);
        friends_t *ttmp = tmp->friends->next;
        for (; ttmp != tmp->friends; ttmp = ttmp->next)
        {
            remove_str(ttmp->friendname);
            fprintf(fp,"[%s]\n",ttmp->friendname);
        }
    }
    fclose(fp);
}
void load_friends(clients *newuser, const char *filename)
{
    if (newuser == NULL || filename == NULL) {
        printf("Error: 用户指针或文件名为空。\n");
        return;
    }

    FILE *fp = fopen(filename, "r");
    if (fp == NULL) {
        perror("friend.txt fail to open");
        exit(1);
    }

    char line[100];
    bool match_user = false;

    while (fgets(line, sizeof(line), fp)) {
        remove_str(line);

        // 匹配 [username]:
        if (strncmp(line, "[username]:", 11) == 0) {
            char username[32] = {0};
            sscanf(line, "[username]:%31s", username);

            // 判断是否是当前登录的用户
            if (strcmp(username, newuser->name) == 0) {
                match_user = true;
            } else {
                match_user = false;  // 下一个用户，停止当前好友加载
            }
            continue;
        }

        // 若未匹配当前用户，跳过
        if (!match_user) continue;

        // 匹配 [friends list]: 行
        if (strncmp(line, "[friends list]:", 15) == 0) {
            continue;  // 不处理此行
        }

        // 匹配 [xxx] 好友名
        if (line[0] == '[' && line[strlen(line) - 1] == ']') {
            char friendname[32] = {0};
            sscanf(line, "[%31[^]]", friendname);

            // 跳过自己
            if (strcmp(friendname, newuser->name) == 0) continue;

            // 检查是否已是好友
            bool already_friend = false;
            for (friends_t *f = newuser->friends->next; f != newuser->friends; f = f->next) {
                if (strcmp(f->friendname, friendname) == 0) {
                    already_friend = true;
                    break;
                }
            }
            if (already_friend) continue;

            // 加入 newuser 的好友列表
            friends_t *newf = calloc(1, sizeof(friends_t));
            strcpy(newf->friendname, friendname);
            newf->next = newuser->friends;
            newf->prev = newuser->friends->prev;
            newuser->friends->prev->next = newf;
            newuser->friends->prev = newf;

            // 查找这个好友用户结构（无论在线与否）
            clients *friend_user = NULL;
            for (clients *p = user->next; p != user; p = p->next) {  // 你可改为 reg_user 遍历
                if (strcmp(p->name, friendname) == 0) {
                    friend_user = p;
                    break;
                }
            }

            // 如果存在该好友用户，为其也添加当前用户为好友（双向）
            if (friend_user != NULL) {
                bool mutual_friend = false;
                for (friends_t *f = friend_user->friends->next; f != friend_user->friends; f = f->next) {
                    if (strcmp(f->friendname, newuser->name) == 0) {
                        mutual_friend = true;
                        break;
                    }
                }
                if (!mutual_friend) {
                    friends_t *newf2 = calloc(1, sizeof(friends_t));
                    strcpy(newf2->friendname, newuser->name);
                    newf2->next = friend_user->friends;
                    newf2->prev = friend_user->friends->prev;
                    friend_user->friends->prev->next = newf2;
                    friend_user->friends->prev = newf2;
                }
            }
        }
    }

    fclose(fp);
}

